package utils

import (
	"github.com/sony/sonyflake"
	"hash/crc32"
	"math"
	"net"
	"strconv"
	"time"
)

var machineId uint16
var sf *sonyflake.Sonyflake

func init() {
	machineId = getMachineId()

	var st sonyflake.Settings
	st.StartTime = time.Date(2023, 1, 5, 0, 0, 0, 0, time.Local) //time.Unix(1591631999,0)
	st.MachineID = func() (uint16, error) {
		return machineId, nil
	}

	sf = sonyflake.NewSonyflake(st)
}

func getMachineId() uint16 {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return 0
	}
	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			val := crc32.ChecksumIEEE(ipnet.IP) % uint32(math.MaxUint16)
			return uint16(val)
		}
	}

	return 0
}

func SnowflakeId() uint64 {
	id, _ := sf.NextID()

	return id
}

func SnowflakeStringId() string {
	id := SnowflakeId()

	return strconv.FormatUint(id, 10)
}
